<?php
/**
 * OAuth2.0 授权接口
 */
class oauthController extends base
{

    private $server = null;

	private $storage = null;

	public function __construct()
    {
        parent::__construct('show');
        $this->initServer();
    }
	
    public function dologin()
    {
		$rurl = common::request('rurl','G','');
		setcookie("rurl",$rurl);
		if(empty($_POST)){
			//人人授权
			$this->loadlib('renren');
			$rr = new RenRen();
			$rrUrl = $rr->authorizeUrl();

			//新浪微博
			include FILE . 'lib/sina.class.php';
			$o = new SaeTOAuthV2();
			$code_url = $o->getAuthorizeURL('http://irun.hupu.com/index.php?c=connect&a=Callback');
			//qq
			include FILE . 'lib/qqConnect/QC.class.php';
			$qc = new QC();
			$qqUrl = $qc->qq_login();
			$this->view->assign('codeUrl', $code_url);
			$this->view->assign('qqUrl', $qqUrl);
			$this->view->assign('staticHost', "http://".$this->config['host']);
			$this->view->assign('rrUrl',$rrUrl);
			$this->view->display('login');
		}else{
			$phone = common::request('phone','P');
			$pwd = common::request('pwd','P');
			if(empty($phone) || empty($pwd)){
				echo "<script>alert('信息不完整！');window.history.go(-1)</script>";
				exit;
			}
			$userInfo = $this->load('user')->getInfoByPhone($phone);
			if(empty($userInfo)){
				echo "<script>alert('用户不存在！');window.history.go(-1)</script>";
				exit;
			}
			if($userInfo['pwd'] != md5($pwd)){
				echo "<script>alert('密码不正确！');window.history.go(-1)</script>";
				exit;
			}
			$time = time();
			$tokenStr = md5($userInfo['uid'] . $time . $this->config['tokenStr']);
			$uid = $this->alphaId->getHash($userInfo['uid']);
			$tokenArr = array($uid, $time, $tokenStr, md5($this->client));
			$token = implode('-', $tokenArr);
			setcookie('joggers_u', $token, time()+864000, '/', '.hupu.com', FALSE, TRUE);
			setcookie('joggers_u', $token, time()+864000, '/', '.ijoggers.com', FALSE, TRUE);
			common::go($rurl);
		}

	}

	

	/**
	 * 授权
	 * @return [type] [description]
	 */
	public function doAuthorize()
	{

		$request = OAuth2\Request::createFromGlobals();
		$response = new OAuth2\Response();

		if (!$this->server->validateAuthorizeRequest($request, $response)) {
			$response->send();
			die;
		}
		$rurl = $_SERVER['REQUEST_URI'];
		$token = isset($_COOKIE['joggers_u']) ? $_COOKIE['joggers_u'] : '';
		if(empty($token)){
			common::go('/oauth/login?rurl='.urlencode($rurl));
		}
		$info = explode('-',$token);
		if(empty($_POST)){
			$uid = $this->alphaId->getNumber($info[0]);
			$userInfo = $this->load('client')->getUserInfo($uid);
			$this->view->assign('info',$userInfo);
			$this->view->assign('staticHost', "http://".$this->config['host']);
			$this->view->display('oauth_authorize');
		}else{
			$openid = $this->alphaId->getNumber($info[0]);
			$is_authorized = ($_POST['authorized'] === 'yes');
			$this->server->handleAuthorizeRequest($request, $response, $is_authorized,$openid);
			if ($is_authorized) {
				//$code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
				$url = $response->getHttpHeader('Location');
				common::go($url);
			}
			$response->send();
		}

	}
	/**
	 * 获取Access Token
	 * @return [type] [description]
	 */
	public function doAccessToken()
	{
		$request = OAuth2\Request::createFromGlobals();
		$this->server->handleTokenRequest($request)->send();
	}

	/**
	 * 初始化OAuth Server
	 * @return [type] [description]
	 */
	private function initServer()
	{
		require_once(FILE."lib/OAuth2/Autoloader.php");
		OAuth2\Autoloader::register();

		$cfg_db = $this->config['mysql'];

		$dsn = "mysql:dbname=".$cfg_db['dbname'].";host=".$cfg_db['ip'];

		$db_table_config = array(
            'client_table' => 'r_oauth_clients',
            'access_token_table' => 'r_oauth_access_tokens',
            'refresh_token_table' => 'r_oauth_refresh_tokens',
            'code_table' => 'r_oauth_authorization_codes',
            'scope_table'  => 'r_oauth_scopes',
        );

		$this->storage = new OAuth2\Storage\Pdo(
			array(
				'dsn' => $dsn,
				'username' => $cfg_db['user'],
				'password' => $cfg_db['pwd']
			),
			$db_table_config
		);
		
		$this->server = new OAuth2\Server($this->storage);
		$this->server->addGrantType(new OAuth2\GrantType\ClientCredentials($this->storage));
		$this->server->addGrantType(new OAuth2\GrantType\AuthorizationCode($this->storage));
		$this->server->addGrantType(new OAuth2\GrantType\RefreshToken($this->storage),array(
			'always_issue_new_refresh_token' => false
		));
	}


	public function doUserInfo(){
		$request = OAuth2\Request::createFromGlobals();
		$token = $request->request['access_token'];
		if(empty($token)){
			echo json_encode(array('error'=>'token error','error_description'=>'token not avilid'));
			exit;
		}
		if (!$this->server->verifyResourceRequest($request)) {
			return $this->server->getResponse()->send();
		}
		$auid = $this->_getUid($token);
		$userInfo = $this->load('client')->getUserInfo($auid);
		$re_data = array(
			'id' => $this->alphaId->getHash($userInfo['uid']),
			'nickname' => $userInfo['nickname'],
			'header'   => $userInfo['header'],
			'header_source' => $userInfo['header_source'],
			'height'  => $userInfo['height'],
			'weight'  => $userInfo['weight'],
			'age'  => $userInfo['age'],
			'gender' => $userInfo['gender'],
			'total_rate' => $userInfo['total_rate'],
			'total_mileage' => $userInfo['total_mileage'],
			'province' => $userInfo['province'],
			'city' => $userInfo['city']
		);
		echo json_encode($re_data);
	}

	public function dorunData(){
		$request = OAuth2\Request::createFromGlobals();
		$token = $request->request['access_token'];
		if(empty($token)){
			echo json_encode(array('error'=>'invalid_token','error_description'=>'The access token provided is invalid'));
			exit;
		}
		if (!$this->server->verifyResourceRequest($request)) {
			return $this->server->getResponse()->send();
		}
		$page = common::request('page', 'P', '1');
		$runDay = intval(common::request('run_day', 'P'));

		$auid = $this->_getUid($token);

		if($runDay)
		{
			$beginTime = strtotime($runDay);
			$endTime = $beginTime + 86400;
		}

		$list = $this->load('run')->getClientRunHistoryData($auid, $page, 0, 'next', 20, $beginTime, $endTime);
		$re_data = array();
		foreach($list as $info){
			$re_data[] = array(
				'rid' => $info['order_id'],
				'run_time' => $info['updatetime'],
				'mileage' => $info['mileage'],
				'elapsedtime' => $info['elapsedtime'],
				'speed' => $info['speed'],
				'legspeed' => $info['legspeed'],
				'calorie' => $info['calorie'],
				'city' => $info['city'],
				'share_img' => $info['share_img'],
				'target_type' => $info['target_type'],
				'target_rate' => $info['target_rate'],
				'run_mood' => $info['run_mood'],
				'expression_id' => $info['expression_id'],
				'medal' => $info['medal'],
				'five_time' => $info['five_time'],
				'ten_time' => $info['ten_time'],
				'half_mtime' => $info['half_mtime'],
				'mara_time' => $info['mara_time'],

			);
		}

		echo json_encode($re_data);

	}

	private function _getUid($token){
		$uid = NULL;
		$info = $this->storage->getAccessToken($token);
		!empty($info) && $uid = $info['user_id'];
		return $uid;

	}

}